package Formularios;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;

public class frmReactivos extends JFrame {

	private JPanel contentPane;
	private JTextField txtCodigo;
	private JTextField txtDescripcion;
	private JTextField txtStockMin;
	private JTextField txtStockOptimo;
	private JTextField txtStockMaximo;
	private JTextField txtExistencia;
	private JComboBox cbUnidadMedida;
	StatusBar sbMensaje;
	
	//teclas Virtuales
	static final int VK_SALTO_DE_LINEA = 10;
	static final int VK_F5 = 116;
	static final int VK_SUPR = 127;
	static final int VK_ESC = 27;
	
	static Statement comando;
	static Connection con;
	private JTextField txtPrecioxKilo;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frmReactivos frame = new frmReactivos();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public frmReactivos() {
		
		general gen = new general();
		try {
			comando = gen.abrirConexion(cNemonicos.IP_GLOBAL,1);
			
			frmReactivos dialog = new frmReactivos();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
			dialog.setLocationByPlatform(true); //centrar dialogo
			
			System.out.println("aqui va algo" + comando.getConnection());
			System.out.println("ya salio del dialogo");
		} catch (ClassNotFoundException | SQLException e1) {
			e1.printStackTrace();
		}
		
		
		setResizable(false);
		setTitle("Captura de Reactivos");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		
		// Centrar
		setLocationRelativeTo(null);				
				
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblCodigo = new JLabel("Codigo: ");
		lblCodigo.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCodigo.setBounds(12, 24, 118, 15);
		contentPane.add(lblCodigo);
		
		JLabel lblDescripcin = new JLabel("Descripción: ");
		lblDescripcin.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDescripcin.setBounds(12, 51, 118, 15);
		contentPane.add(lblDescripcin);
		
		JLabel lblUnMedida = new JLabel("Ud. Medida: ");
		lblUnMedida.setHorizontalAlignment(SwingConstants.RIGHT);
		lblUnMedida.setBounds(12, 78, 118, 15);
		contentPane.add(lblUnMedida);
		
		JLabel lblStockMin = new JLabel("Stock Min: ");
		lblStockMin.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStockMin.setBounds(12, 105, 118, 15);
		contentPane.add(lblStockMin);
		
		JLabel lblSrockOptimo = new JLabel("Srock Optimo: ");
		lblSrockOptimo.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSrockOptimo.setBounds(12, 132, 118, 15);
		contentPane.add(lblSrockOptimo);
		
		JLabel lblStockMaximo = new JLabel("Stock Maximo :");
		lblStockMaximo.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStockMaximo.setBounds(12, 159, 118, 15);
		contentPane.add(lblStockMaximo);
		
		txtCodigo = new JTextField();
		txtCodigo.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {
				sbMensaje.setText("[ ENTER ] Continuar");
			}
		});
		txtCodigo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == VK_SALTO_DE_LINEA)
				{
					if ( txtCodigo.getText().length() == 0 )
					{
						txtCodigo.setText(String.valueOf(general.consultarFolio(comando, cNemonicos.FOLIO_REACTIVOS, cNemonicos.SIGUIENTE_SECUENCIA)));
						txtDescripcion.requestFocus();
					}
					else
					{
						boolean bContinuar = conslutar(Integer.parseInt(txtCodigo.getText()));
						if (bContinuar == false)
						{
							limpiarReactivos();
						}
						else
						{
							sbMensaje.setText("[ SUPR ] Eliminar Reactivo [ ESC ] Limpiar");
						}
						txtDescripcion.requestFocus();
					}
					
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtCodigo.getText().length() == 3) {
					e.consume();
				}
			}
		});
		txtCodigo.setBounds(149, 22, 58, 19);
		contentPane.add(txtCodigo);
		txtCodigo.setColumns(10);
		
		txtDescripcion = new JTextField();
		txtDescripcion.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == VK_SALTO_DE_LINEA)
				{
					cbUnidadMedida.requestFocus();
				}
				if ( e.getKeyCode() == VK_ESC )
				{
					limpiarTodo();
					txtCodigo.requestFocus();
					sbMensaje.setText("[ ENTER ] Continuar");
				}
				if ( e.getKeyCode() == VK_SUPR )
				{
					int op = JOptionPane.showOptionDialog (null,"Desea eliminar el producto Actual ","Eliminar Producto",JOptionPane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR","CANCELAR"},"ACEPTAR");
					if ( op == 0)
					{
						if ( eliminarReactivo(Integer.parseInt(txtCodigo.getText())))
						{
							limpiarTodo();
							txtCodigo.requestFocus();
						}
					}
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if (((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtDescripcion.getText().length() == 50) {
					e.consume();
				}
			}
		});
		txtDescripcion.setInputVerifier(new InputVerifier() {
			
			@Override
			public boolean verify(JComponent arg0) {
				if ( txtDescripcion.getText().length() > 0)
				{
					return true;
				}
				else
				{
					JOptionPane.showOptionDialog (null,"Favor de Capturar la Descripción","Datos Incorrectos",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
					txtDescripcion.requestFocus();
					return false;
				}
				
			}
		});
		txtDescripcion.setBounds(149, 49, 202, 19);
		contentPane.add(txtDescripcion);
		txtDescripcion.setColumns(10);
		
		txtStockMin = new JTextField();
		txtStockMin.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == VK_SALTO_DE_LINEA)
				{
					txtStockOptimo.requestFocus();
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtStockMin.getText().length() == 2) {
					e.consume();
				}
			}
		});
		txtStockMin.setInputVerifier(new InputVerifier() {
			
			@Override
			public boolean verify(JComponent arg0) {
				if ( txtStockMin.getText().length() > 0)
				{
					return true;
				}
				else
				{
					JOptionPane.showOptionDialog (null,"Favor de Capturar el Stock Minimo","Datos Incorrectos",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
					txtStockMin.requestFocus();
					return false;
				}
				
			}
		});
		txtStockMin.setBounds(148, 103, 31, 19);
		contentPane.add(txtStockMin);
		txtStockMin.setColumns(10);
		
		txtStockOptimo = new JTextField();
		txtStockOptimo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == VK_SALTO_DE_LINEA) {
					txtStockMaximo.requestFocus();
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtStockOptimo.getText().length() == 2) {
					e.consume();
				}
			}
		});
		txtStockOptimo.setInputVerifier(new InputVerifier() {
			
			@Override
			public boolean verify(JComponent arg0) {
				if ( txtStockOptimo.getText().length() > 0)
				{
					return true;
				}
				else
				{
					JOptionPane.showOptionDialog (null,"Favor de Capturar el Stock Optimo","Datos Incorrectos",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
					txtStockOptimo.requestFocus();
					return false;
				}
				
			}
		});
		txtStockOptimo.setBounds(149, 130, 31, 19);
		contentPane.add(txtStockOptimo);
		txtStockOptimo.setColumns(10);
		
		txtStockMaximo = new JTextField();
		txtStockMaximo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == VK_SALTO_DE_LINEA) {
					txtExistencia.requestFocus();
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtStockMaximo.getText().length() == 2) {
					e.consume();
				}
			}
		});
		txtStockMaximo.setInputVerifier(new InputVerifier() {
			
			@Override
			public boolean verify(JComponent arg0) {
				if ( txtStockMaximo.getText().length() > 0)
				{
					return true;
				}
				else
				{
					JOptionPane.showOptionDialog (null,"Favor de Capturar el Stock Maximo","Datos Incorrectos",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
					txtStockMaximo.requestFocus();
					return false;
				}
				
			}
		});
		txtStockMaximo.setBounds(149, 157, 31, 19);
		contentPane.add(txtStockMaximo);
		txtStockMaximo.setColumns(10);
		
		JLabel lblExistencia = new JLabel("Existencia :");
		lblExistencia.setHorizontalAlignment(SwingConstants.RIGHT);
		lblExistencia.setBounds(22, 186, 108, 15);
		contentPane.add(lblExistencia);
		
		txtExistencia = new JTextField();
		txtExistencia.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == VK_F5)
				{
					if (txtExistencia.getText().length() > 0)
					{
						if ( guardar())
						{
							limpiarTodo();
							txtCodigo.requestFocus();
							sbMensaje.setText("[ ENTER ] Continuar");
						}
					}
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				else
				{
					sbMensaje.setText("[ F5 ] Guardar");
				}
				if (txtExistencia.getText().length() == 2) {
					e.consume();
				}
			}
		});
		txtExistencia.setInputVerifier(new InputVerifier() {
			
			@Override
			public boolean verify(JComponent arg0) {
				if ( txtExistencia.getText().length() > 0)
				{
					return true;
				}
				else
				{
					JOptionPane.showOptionDialog (null,"Favor de Capturar la Existencia","Datos Incorrectos",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
					txtExistencia.requestFocus();
					return false;
				}
				
			}
		});
		txtExistencia.setBounds(149, 184, 31, 19);
		contentPane.add(txtExistencia);
		txtExistencia.setColumns(10);
		
		cbUnidadMedida = new JComboBox();
		cbUnidadMedida.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == VK_SALTO_DE_LINEA) {
					txtPrecioxKilo.requestFocus();
				}
			}
		});
		cbUnidadMedida.setModel(new DefaultComboBoxModel(new String[] {"Kg.", "Lt."}));
		cbUnidadMedida.setBounds(148, 73, 59, 24);
		contentPane.add(cbUnidadMedida);
		
		sbMensaje = new StatusBar();
		sbMensaje.setText("[ ENTER ] Continuar [ ESC ] Salir");
		sbMensaje.setHorizontalAlignment(SwingConstants.CENTER);
		sbMensaje.setBounds(0, 243, 448, 24);
		contentPane.add(sbMensaje);
		
		JLabel lblPrecioXKilo = new JLabel("Precio x UM :");
		lblPrecioXKilo.setBounds(216, 80, 99, 15);
		contentPane.add(lblPrecioXKilo);
		
		txtPrecioxKilo = new JTextField();
		txtPrecioxKilo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == cNemonicos.VK_SALTO_DE_LINEA && txtPrecioxKilo.getText().length() > 0 )
				{
					txtStockMin.requestFocus();
				}
			}
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtPrecioxKilo.getText().length() == 4) {
					e.consume();
				}
			}
		});
		txtPrecioxKilo.setBounds(317, 78, 53, 19);
		contentPane.add(txtPrecioxKilo);
		txtPrecioxKilo.setColumns(10);
		setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{txtCodigo, txtDescripcion, cbUnidadMedida, txtPrecioxKilo, txtStockMin, txtStockOptimo, txtStockMaximo, txtExistencia}));
	}
	
	
	public boolean conslutar(int iCodigo)
	{
		boolean bResultado = false;
		
		
		try{
			
			//Una variable String para almacenar la sentencia SQL
			String query = "select codigo,trim(descripcion) as descripcion,unidadmedida,stockmin,stockoptimo,stockmaximo,existencia from reactivos where codigo = " + iCodigo + ";";
			
			ResultSet resultado = comando.executeQuery(query);
			

			//Ejecutamos la consulta SQL
			if (resultado.next()) {
				txtDescripcion.setText(resultado.getString("descripcion"));
				cbUnidadMedida.setSelectedItem(resultado.getString("unidadmedida"));
				txtStockMin.setText(String.valueOf(resultado.getInt("stockmin")));
				txtStockOptimo.setText(String.valueOf(resultado.getInt("stockoptimo")));
				txtStockMaximo.setText(String.valueOf(resultado.getInt("stockmaximo")));
				txtExistencia.setText(String.valueOf(resultado.getInt("existencia")));
				bResultado = true;
			}

			}
			catch( SQLException e )
			{
				//Por si ocurre un error
				System.out.println(e.getMessage());
				int op = JOptionPane.showOptionDialog (null,e.getMessage(),"Entrada Invalidad",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
				if (op == 0)
				{
					txtCodigo.requestFocus();
				}
			}
					
			
		return bResultado;		
	}
	
	public void limpiarReactivos()
	{
		txtDescripcion.setText("");
		cbUnidadMedida.setSelectedIndex(-1);
		txtPrecioxKilo.setText("");
		txtStockMin.setText("");
		txtStockOptimo.setText("");
		txtStockMaximo.setText("");
		txtExistencia.setText("");
	}
	
	public void limpiarTodo()
	{
		txtCodigo.setText("");
		limpiarReactivos();
	}
	
	public boolean guardar()
	{
		boolean bResultado = true;
		
		int iCodigo = Integer.parseInt(txtCodigo.getText());
		double dPrecioxKilo = Double.parseDouble(txtPrecioxKilo.getText());
		String sNombre = txtDescripcion.getText();
		String sUnidadMedida = (String) cbUnidadMedida.getSelectedItem();
		int iStockMin = Integer.parseInt(txtStockMin.getText());
		int iStockOptimo = Integer.parseInt(txtStockOptimo.getText());
		int iStockMaximo = Integer.parseInt(txtStockMaximo.getText());
		int iExistencia = Integer.parseInt(txtExistencia.getText());//la existencia se va a multiplicar por mil para guardar en gramos o mililitros

		String query;
		query = String.format("select GuardarReactivo(" + iCodigo + ",'%s','%s', "+ dPrecioxKilo + ',' + iStockMin + "," + iStockOptimo + "," + iStockMaximo + "," + iExistencia*1000 + ")", sNombre, sUnidadMedida );
		System.out.println(query);
	
		cTotal insertar = new cTotal(comando);
		try {
			insertar.ejecutar(query);

		} catch (SQLException e) {
			general.grabarError("frmReactivos", "guardar", -1, query, e.getMessage(),"Error al insertar Reactivos");
			// TODO Auto-generated catch block
			bResultado = false;
			e.printStackTrace();
		}

		return bResultado;		
	}
	
	public boolean eliminarReactivo(int iCodigo)
	{
		boolean bResultado = true;
		int iRenglon = 0;
		try {

			// Una variable String para almacenar la sentencia SQL
			String query = "delete from reactivos where codigo = " + iCodigo + ";";
			System.out.println(query);

			//Ejecutamos la consulta SQL
			comando.executeUpdate(query);
			//sbMensaje.setText("Producto Eliminado Con Exito");
			

		} catch (SQLException e) {
			bResultado = false;
			// Por si ocurre un error
			System.out.println(e.getMessage());
			int op = JOptionPane.showOptionDialog(null, e.getMessage(),
					"Entrada Invalidad", JOptionPane.YES_OPTION,
					JOptionPane.ERROR_MESSAGE, null,
					new Object[] { "ACEPTAR" }, "ACEPTAR");
			if (op == 0) {

			}
		}

		return bResultado;
	}
}
